package com.quanshu.exchange.ui.gui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gyf.barlibrary.ImmersionBar;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.quanshu.exchange.R;
import com.quanshu.exchange.support.api.UserInterface;
import com.quanshu.exchange.support.chat.ChatConstant;
import com.quanshu.exchange.support.chat.ChatHelper;
import com.quanshu.exchange.support.db.GroupDao;
import com.quanshu.exchange.support.db.UserDao;
import com.quanshu.exchange.support.db.core.DBController;
import com.quanshu.exchange.support.entity.GroupEntity;
import com.quanshu.exchange.support.entity.UserEntity;
import com.quanshu.exchange.support.net.BaseResponse;
import com.quanshu.exchange.support.net.core.BaseObserver;
import com.quanshu.exchange.support.net.core.BaseTransformer;
import com.quanshu.exchange.support.net.core.NetClient;
import com.quanshu.exchange.support.utils.AppUtils;
import com.quanshu.exchange.support.utils.LogUtil;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.support.utils.ToastHelper;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.exchange.ui.base.BaseFragment;
import com.quanshu.exchange.ui.gui.login.LoginAnotherDeviceActivity;
import com.quanshu.exchange.ui.gui.message.MessageFragment;
import com.quanshu.exchange.ui.gui.profile.ProfileFragment;
import com.quanshu.exchange.ui.gui.shop_store.ShopStoreFragment;
import com.quanshu.exchange.ui.widget.dragindicator.DragIndicatorView;
import com.quanshu.shop.main.view.ShopMainFragment;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.quanshu.exchange.support.config.Config.ACTION_NOTIFY_CHANGED;

/**
 * Created by jye on 2017/12/6.
 */

public class HomePageActivity extends BaseActivity implements ShopMainFragment.OnFragmentInteractionListener {

    @BindView(R.id.home_content)
    FrameLayout homeContent;
    @BindView(R.id.tab_shop_store)
    LinearLayout tabShopStore;
    @BindView(R.id.tab_message)
    RelativeLayout tabMessage;
    @BindView(R.id.tab_profile)
    LinearLayout tabProfile;
    @BindView(R.id.tab_shop_store_image)
    ImageView tabShopStoreImage;
    @BindView(R.id.tab_shop_store_text)
    TextView tabShopStoreText;
    @BindView(R.id.tab_message_image)
    ImageView tabMessageImage;
    @BindView(R.id.tab_message_text)
    TextView tabMessageText;
    @BindView(R.id.tab_profile_image)
    ImageView tabProfileImage;
    @BindView(R.id.tab_profile_text)
    TextView tabProfileText;
    @BindView(R.id.message_dot_view)
    DragIndicatorView msgDotView;

    private FragmentManager fragmentManager;
    private BaseFragment currentFragment;
//    private ShopStoreFragment shopStoreFragment;
    private ShopMainFragment shopMainFragment;
    private MessageFragment messageFragment;
    private ProfileFragment profileFragment;
    private LocalBroadcastManager broadcastManager;
    private BroadcastReceiver broadcastReceiver;

    private boolean isFetchingContacts = false;
    private boolean isFetchingGroups = false;
    private MyMessageListener messageListener;

    // user logged into another device
    public boolean isConflict = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initIntent();
        setContentView(R.layout.activity_home_layout);
        ButterKnife.bind(this);
        ImmersionBar.with(this).init();
        initView();
        initListener();
        initViewPageIndicator(1);
        asyncMessage();
    }

    private void asyncMessage() {
        // 如果当前用户存在
        if (currentUser != null && currentUser.getMemberid() != null && currentUser.getMemberid().length() > 0) {
            registerBroadcastReceiver();
            asyncFetchContactsFromServer();
            asyncFetchGroupsFromServer();
            showExceptionDialogFromIntent(getIntent());
        }
    }

    private void initIntent() {
        if (getIntent() != null) {
            boolean login_by_other_device = getIntent().getBooleanExtra(ChatConstant.ACCOUNT_CONFLICT, false);
            if (login_by_other_device) {
                ChatHelper.getInstance().logout(true, null);
                DBController.reset();
                doChangeDevice();
                return;
            }
        }
    }

    private void doChangeDevice() {
        Intent intent = new Intent(this, LoginAnotherDeviceActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putBoolean(ChatConstant.ACCOUNT_CONFLICT, isConflict);
//        outState.putBoolean(ChatConstant.ACCOUNT_REMOVED, isCurrentAccountRemoved);
        super.onSaveInstanceState(outState);
    }

    private void showExceptionDialogFromIntent(Intent intent) {
        boolean conflict = intent.getBooleanExtra(ChatConstant.ACCOUNT_CONFLICT, false);
        if (conflict) {
            ChatHelper.getInstance().logout(true, null);
            DBController.reset();
            doChangeDevice();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        showExceptionDialogFromIntent(intent);
    }

    //我把之前的注释删了
    private void initView() {
        fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction()
                .setCustomAnimations(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
//        if (shopStoreFragment == null) {
//            shopStoreFragment = ShopStoreFragment.newInstance();
//        }
        if (shopMainFragment==null){
            shopMainFragment=ShopMainFragment.newInstance("","",this);
        }
//        if (!shopStoreFragment.isAdded()) {
////            transaction.add(R.id.home_content, shopStoreFragment).commitAllowingStateLoss();
////        } else {
////            transaction.show(shopStoreFragment).commitAllowingStateLoss();
////        }
////        currentFragment = shopStoreFragment;
        if (!shopMainFragment.isAdded()){
            transaction.add(R.id.home_content,shopMainFragment).commitAllowingStateLoss();
        }else {
            transaction.show(shopMainFragment).commitAllowingStateLoss();
        }
        currentFragment = shopMainFragment;
    }

    private void initListener() {

        RxViewHelper.getInstance().clicks(tabShopStore, aVoid -> {
            initViewPageIndicator(0);
        });
        RxViewHelper.getInstance().clicks(tabMessage, aVoid -> {
            initViewPageIndicator(1);
        });
        RxViewHelper.getInstance().clicks(tabProfile, aVoid -> {
            initViewPageIndicator(2);
        });
        messageListener = new MyMessageListener();
        EMClient.getInstance().chatManager().addMessageListener(messageListener);
    }

    private void initViewPageIndicator(int position) {
        if (position == 0) {
            tabShopStoreImage.setSelected(true);
            tabShopStoreText.setSelected(true);
            tabMessageImage.setSelected(false);
            tabMessageText.setSelected(false);
            tabProfileImage.setSelected(false);
            tabProfileText.setSelected(false);
            FragmentTransaction transaction = fragmentManager.beginTransaction()
                    .setCustomAnimations(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
//            addOrShowFragment(R.id.home_content, transaction, shopStoreFragment);
            addOrShowFragment(R.id.home_content,transaction,shopMainFragment);

        } else if (position == 1) {
            tabShopStoreImage.setSelected(false);
            tabShopStoreText.setSelected(false);
            tabMessageImage.setSelected(true);
            tabMessageText.setSelected(true);
            tabProfileImage.setSelected(false);
            tabProfileText.setSelected(false);
            msgDotView.setVisibility(View.GONE);
            if (messageFragment == null) {
                messageFragment = MessageFragment.newInstance();
            }
            FragmentTransaction transaction = fragmentManager.beginTransaction()
                    .setCustomAnimations(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
            addOrShowFragment(R.id.home_content, transaction, messageFragment);

        } else if (position == 2) {
            tabShopStoreImage.setSelected(false);
            tabShopStoreText.setSelected(false);
            tabMessageImage.setSelected(false);
            tabMessageText.setSelected(false);
            tabProfileImage.setSelected(true);
            tabProfileText.setSelected(true);
            if (profileFragment == null) {
                profileFragment = ProfileFragment.newInstance();
            }
            FragmentTransaction transaction = fragmentManager.beginTransaction()
                    .setCustomAnimations(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
            addOrShowFragment(R.id.home_content, transaction, profileFragment);
        }
    }

    /**
     * 添加或者显示 fragment
     *
     * @param transaction
     * @param fragment
     */
    protected void addOrShowFragment(int containerViewId, FragmentTransaction transaction, Fragment fragment) {
        if (currentFragment == fragment)
            return;
        if (!fragment.isAdded()) { // 如果当前fragment未被添加，则添加到Fragment管理器中
            transaction.hide(currentFragment).add(containerViewId, fragment).commitAllowingStateLoss();
        } else {
            transaction.hide(currentFragment).show(fragment).commitAllowingStateLoss();
        }
        currentFragment = (BaseFragment) fragment;
    }

    private void registerBroadcastReceiver() {
        broadcastManager = LocalBroadcastManager.getInstance(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_NOTIFY_CHANGED);
        broadcastReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                runOnUiThread(() -> {
                    msgDotView.setVisibility(View.VISIBLE);
                    if (currentFragment instanceof MessageFragment) {
                        LogUtil.print(Log.INFO, "收到通知");
                        if (intent.getAction().equals(ACTION_NOTIFY_CHANGED)) {
                            ((MessageFragment) currentFragment).doRefreshNotify();
                        }
                    }
                });
            }
        };
        broadcastManager.registerReceiver(broadcastReceiver, intentFilter);
    }

    private void unregisterBroadcastReceiver() {
        if (broadcastManager != null) {
            broadcastManager.unregisterReceiver(broadcastReceiver);
        }
    }

    @Override
    protected void onDestroy() {
        unregisterBroadcastReceiver();
        EMClient.getInstance().chatManager().removeMessageListener(messageListener);
        super.onDestroy();
    }

    private void asyncFetchContactsFromServer() {
        if (isFetchingContacts == false) {
            isFetchingContacts = true;
            NetClient.getInstance()
                    .getNetService(UserInterface.class)
                    .getFriendList(AppUtils.getSignParams(currentUser.getMemberid()), currentUser.getMemberid())
                    .compose(new BaseTransformer<>(this))
                    .subscribe(new BaseObserver<BaseResponse<List<UserEntity>>>() {
                        @Override
                        public void onSuccess(BaseResponse<List<UserEntity>> response) {
                            List<UserEntity> userEntities = response.getInfo();
                            UserDao.getInstance().save(userEntities);
                        }


                    });
        }
    }

    private void asyncFetchGroupsFromServer() {
        if (isFetchingGroups == false) {
            isFetchingGroups = true;
            NetClient.getInstance()
                    .getNetService(UserInterface.class)
                    .getMyGroups(AppUtils.getSignParams(currentUser.getMemberid()), currentUser.getMemberid())
                    .compose(new BaseTransformer<>(this))
                    .subscribe(new BaseObserver<BaseResponse<List<GroupEntity>>>() {
                        @Override
                        public void onSuccess(BaseResponse<List<GroupEntity>> response) {
                            if (response.getInfo() != null) {
                                List<GroupEntity> groupEntities = response.getInfo();
                                GroupDao.getInstance().save(groupEntities);
                            }
                        }
                    });
        }
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }

    class MyMessageListener implements EMMessageListener {
        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            runOnUiThread(() -> {
                msgDotView.setVisibility(View.VISIBLE);
                if (currentFragment instanceof MessageFragment) {
                    ((MessageFragment) currentFragment).doRefreshMessage();
                }
            });
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
            if (messages != null) {
                for (EMMessage emMessage : messages) {
                    EMCmdMessageBody cmdMsgBody = (EMCmdMessageBody) emMessage.getBody();
                    if (cmdMsgBody != null) {
                        String action = cmdMsgBody.action();//获取自定义action
                        if (action != null && action.equals(ChatConstant.Chat_ext_attr_is_toAll)) {
                            EMConversation conversation = EMClient.getInstance().chatManager().getConversation(emMessage.getTo(),
                                    AppUtils.getConversationType(ChatConstant.CHAT_TYPE_GROUP), false);
                            if (conversation != null) {
                                emMessage.setAttribute(ChatConstant.Chat_ext_attr_is_toAll, true);
                                conversation.updateMessage(emMessage);
                            }
                        } else if (action != null && action.equals("group_visible")) {
                            boolean visible = emMessage.getBooleanAttribute("visible", false);
                            String groupId = emMessage.getTo();
                            GroupEntity groupEntity = GroupDao.getInstance().query(groupId);
                            if (groupEntity != null) {
                                if (visible) {
                                    groupEntity.setVisible(1);
                                } else {
                                    groupEntity.setVisible(0);
                                }
                                GroupDao.getInstance().save(groupEntity);
                            }
                        }
                    }
                }
            }
        }

        @Override
        public void onMessageRead(List<EMMessage> messages) {
        }

        @Override
        public void onMessageDelivered(List<EMMessage> messages) {
        }

        @Override
        public void onMessageRecalled(List<EMMessage> messages) {
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
        }
    }

    private long mkeyTime;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (currentFragment instanceof ShopStoreFragment) {
                boolean webViewCanBack = ((ShopStoreFragment) currentFragment).onKeyDown(keyCode);
                if (!webViewCanBack) {
                    if ((System.currentTimeMillis() - mkeyTime) > 1000) {
                        mkeyTime = System.currentTimeMillis();
                        ToastHelper.toast("再按一次退出程序");
                    } else {
                        finish();
                    }
                    return true;
                } else {
                    ((ShopStoreFragment) currentFragment).onKeyDown(keyCode);
                }
                return true;
            } else {
                if ((System.currentTimeMillis() - mkeyTime) > 1000) {
                    mkeyTime = System.currentTimeMillis();
                    ToastHelper.toast("再按一次退出程序");
                } else {
                    finish();
                }
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

}
